package com.sc.ifs.consultComment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.mapper.consultComment.ConsultCommentMapper;
import com.sc.dal.model.consultComment.ConsultComment;
import com.sc.dal.model.member.Member;
import com.sc.dal.model.order.Order;
import com.sc.dal.model.order.Products;
import com.sc.dal.model.seller.Seller;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.order.OrderService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.FileUtil;
import com.sc.util.data.JsonUtils;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;

/**
 * 咨询、评论、浏览管理
 * @author xiongyong
 * @日期 Mar 17, 2017 9:20:34 AM
 */
@Controller
@RequestMapping(value="app/consultComment")
public class ConsultCommentController {
	private final Logger logger = LoggerFactory.getLogger(ConsultCommentController.class); 
	
	@Autowired
	private ConsultCommentService consultCommentService;
	
	@Autowired
	private OrderService orderService;
	
	/**
	 * 根据条件查询咨询、评价、浏览内容数据
	 * type : 1、咨询内容 2、评价晒单 3、我的足迹',
	 * @param request
	 * @return
	 */
	@RequestMapping(value="selectList")
	@ResponseBody
	public Map<String, Object> selectList(HttpServletRequest request,Integer currPage, Integer pageSize){
		//从session里获取用户的登录信息
		/*
		 * 从session里获取用户名
		 * UserFormMap user = (UserFormMap) request.getSession().getAttribute("userSession");
		String accountName = user.get("accountName").toString();  //修改人
*/		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		int totalRecords = 0;	//总记录数
		int totalPage = 0;		//总页数
		List<Map<String, Object>> resultList = null;
		String type = request.getParameter("type");
		String accountName = request.getParameter("accountName"); //获取用户名
		String memeberId = request.getParameter("memeberId"); //会员ID
		if(type==null || "".equals(type)){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
			logger.warn("type查询参数为空！");
		}else{
			try {
				Map<String,Object> paramMap = new HashMap<String,Object>();
				paramMap.put("type", type);
				String goodsId = request.getParameter("goodsId");
				if(goodsId!=null && !"".equals(goodsId)){
					paramMap.put("goodsId", goodsId);
				}
				if(accountName!=null && !"".equals(accountName)){
					paramMap.put("accountName", accountName);
				}
				if(Common.isNotEmpty(memeberId)){
					paramMap.put("creater", memeberId);
				}
				
				//我的足迹不等3，如其下判断
				if(!"3".equals(type)){
					String status = request.getParameter("status");
					//status【咨询状态：0：全部数据 1：已回复  2：未回复  】【评价状态：0：全部 1：差评  2：中评  3：好评  4：有图评价】 
					if(status!=null && !"".equals(status)){
						paramMap.put("status", status);
					//status =4  根据条件查询有图片的数据
					/*}else if(status!=null && !"".equals(status) && "4".equals(status)){
						paramMap.put("filePicture", "");
					//status =0  根据条件查询所有的数据
					}*/
					}else{
						paramMap.put("status", null);
					}
				}else{
					paramMap.put("status", "status");
				}
				
				PaginationBean<Map<String,Object>> pagination = this.consultCommentService.getPagingDatas(paramMap, currPage, pageSize, "count","select",ConsultCommentMapper.class);
				resultList = pagination.getPageList();//返回数据
				totalRecords = pagination.getTotalRecords();//返回行数
				totalPage = pagination.getTotalPage();
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				resultMap.put("data", resultList);
				resultMap.put("pages", totalPage);
				resultMap.put("count", totalRecords);
			} catch (Exception e) {
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.error("查询咨询、评价信息数据异常"+e);
				throw new ScBizException("查询咨询、评价信息数据异常！", e);
			}
		}
		return resultMap;
	}
	
	
	
	/**
	 *    针对个人评价晒单
	 * 参数传递
	 * mId    :  用户ID
	 * status :  0：全部 1：差评  2：中评  3：好评  4：有图评价
	 * type   :  1、咨询内容   2、评价晒单 3、我的足迹',
	 * @param request
	 * @return
	 */
	@RequestMapping(value="selectEvaluateList")
	@ResponseBody
	public Map<String, Object> selectEvaluateList(HttpServletRequest request,Integer currPage, Integer pageSize){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		int totalRecords = 0;	//总记录数
		int totalPage = 0;		//总页数
		List<Map<String, Object>> resultList = null;
		try {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("type", Constants.TYPE_B);
			String memberId = request.getParameter("memberId");
			if(memberId==null || "".equals(memberId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				logger.warn("json的param参数传递出错！");
				return resultMap;
			}
			paramMap.put("memberId", memberId);
			//我的足迹不等3，如其下判断
			String status = request.getParameter("status");
			//status【咨询状态：0：全部数据 1：已回复  2：未回复  】
			//      【评价状态：0：全部 1：差评  2：中评  3：好评  4：有图评价】 
			if(status!=null && !"".equals(status)){
				paramMap.put("status", status);
			}else{
				paramMap.put("status", null);
			}
			PaginationBean<Map<String,Object>> pagination = this.consultCommentService.getPagingDatas(paramMap, currPage, pageSize, "selectEvaluateCount","selectEvaluate",ConsultCommentMapper.class);
			resultList = pagination.getPageList();//返回数据
			totalRecords = pagination.getTotalRecords();//返回行数
			totalPage = pagination.getTotalPage();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			resultMap.put("data", resultList);
			resultMap.put("pages", totalPage);
			resultMap.put("count", totalRecords);
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询个人评价信息数据异常"+e);
			throw new ScBizException("查询个人评价信息数据异常！", e);
		}
		return resultMap;
	}
	
	
	/**
	 * 提交咨询内容、评价内容数据
	 * type : 1、咨询内容 2、评价晒单 3、我的足迹',
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addConsultComment")
	@ResponseBody
	public Map<String, Object> addConsultComment(HttpServletRequest request,String param){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		String commentPath = "imgUrl\\";
		String imgUrl = FileUtil.upload(request, "filePicture", commentPath, ConfigBeanAdapter.fileSaveAddress);
		String imgUrl2 = FileUtil.upload(request, "filePicture2", commentPath, ConfigBeanAdapter.fileSaveAddress);
		String imgUrl3 = FileUtil.upload(request, "filePicture3", commentPath, ConfigBeanAdapter.fileSaveAddress);
		logger.debug("地址信息:"+imgUrl);
		if(param==null){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
			logger.warn("json的param参数传递出错！");
		}else{
			try {
				ConsultComment model = JSON.parseObject(param, ConsultComment.class);   
				String type = model.getType();
				String orderId = model.getOrderId();
				if(model==null || type==null || "".equals(type)){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
					logger.warn("type参数传递出错！");
					return resultMap;
				}
				if("2".equals(type)){
					if(Common.isEmpty(orderId)){
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_ORDER_ID_IS_NULL);
						logger.warn("订单ID参数传递出错！");
						return resultMap;
					}
				}
				//校验咨询内容必填项
				if("1".equals(type)){
					if(model.getConsultContent()==null || "".equals(model.getConsultContent())){
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_CONSULT_PARAM);
						logger.warn("参数传递出错！");
						return resultMap;
					}
				}
				ConsultComment record = this.getByConsultComment(model,imgUrl,imgUrl2,imgUrl3);
				//该字段如不为空，则是追加评论
				String parentId = request.getParameter("id");
				if(Common.isNotEmpty(parentId))
					record.setParentId(new Integer(parentId));
				int j = consultCommentService.insertByConsultComment(record);
				if(j>0){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
					logger.warn("数据保存成功！");
					//修改订单评论状态为已评论
					if(Common.isNotEmpty(orderId) && "2".equals(type)){
						if(j>0){
							logger.warn("数据保存成功！");
							if (resultMap.get("resultSuccess") != null&& resultMap.get("resultSuccess").toString().equals("true")) {
								this.orderService.updateOrderAndOrderDetailCommentStatus(orderId, new Integer(model.getGoodsId()));
								logger.warn("订单评论状态修改成功！");
							}
						}
						/*Order order =new Order();
						order.setOrderId(orderId);
						order.setIsComment(Constants.OrderDetail.OrderStatus.IS_COMMENTB);
						int updateOrderComment = orderService.updateOrder(order);
					    if(updateOrderComment > 0){
					    	logger.warn("订单评论状态修改成功！");
					    }*/
					}
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
					logger.warn("数据保存出错！");
				}
			} catch (Exception e) {
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
				logger.error("数据保存异常"+e);
				throw new ScBizException("数据保存异常！", e);
			}
		}
		return resultMap;
	}
	
	/**
	 * 根据条件查询咨询详情信息
	 * type : 1、咨询内容 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="selectConsultDetail")
	@ResponseBody
	public Map<String, Object> selectConsultDetail(HttpServletRequest request){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		//String type = request.getParameter("type");
		try {
			/*Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("type", type);*/
			String id = request.getParameter("id");
			if(id==null || "".equals(id)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				logger.warn("type查询参数为空！");
				return resultMap;
			}
			ConsultComment data = consultCommentService.selectConsultDetail(new Integer(id));
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, data);
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询咨询、评价详情信息数据异常"+e);
			throw new ScBizException("查询咨询、评价详情信息数据异常！", e);
		}
		return resultMap;
	}
	
	
	
	
	
	/**
	 * 提交咨询内容、评价内容数据
	 * type : 1、咨询内容 2、评价晒单 3、我的足迹',
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addConsultCommentTest")
	@ResponseBody
	public Map<String, Object> addConsultCommentTest(HttpServletRequest request,String param,@RequestParam(value="filePicture", required=false) MultipartFile file){
		String matchPath="imgUrl\\";
		String imgUrl=FileUtil.upload(request, file.getOriginalFilename(), matchPath, ConfigBeanAdapter.fileSaveAddress);
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		return resultMap;
	}
	
	
	/**
	 * 组合咨询、评价对象信息数据
	 * @param model 
	 * @param imgUrl
	 * @param imgUrl2
	 * @param imgUrl3
	 * @return
	 */
	public ConsultComment getByConsultComment(ConsultComment model,String imgUrl,String imgUrl2,String imgUrl3){
		String type = model.getType();
		ConsultComment record = new ConsultComment();
		//咨询内容
		if(type!=null && "1".equals(type)){
			record.setGoodsId(model.getGoodsId());//商品ID
			record.setConsultContent(model.getConsultContent()); //咨询内容
			record.setStatus("2");  //提交状态  0 ：全部数据 ；1：已回复 2：未回复
		//评价内容	
		}else if(type!=null && "2".equals(type)){
			record.setGoodsId(model.getGoodsId());//商品ID
			record.setOrderId(model.getOrderId());//商品订单Id
			record.setSpecInfo(model.getSpecInfo());
			String goodsSatisfaction = model.getGoodsSatisfaction(); //评价内容
			if(goodsSatisfaction!=null && "5".equals(goodsSatisfaction)){
				record.setStatus("3");  //好评
			}else if(goodsSatisfaction!=null && ("4".equals(goodsSatisfaction)||"3".equals(goodsSatisfaction))){
				record.setStatus("2");  //中评
			}else if(goodsSatisfaction!=null && ("2".equals(goodsSatisfaction)||"1".equals(goodsSatisfaction))){
				record.setStatus("1");  //差评
			}
			//上传1图片
			if(imgUrl!=null && !"1".equals(imgUrl)){
				record.setFilePicture(imgUrl);
			}
			//上传2图片
			if(imgUrl2!=null && !"1".equals(imgUrl2)){
				record.setFilePicture2(imgUrl2);
			}
			//上传3图片
			if(imgUrl3!=null && !"1".equals(imgUrl3)){
				record.setFilePicture3(imgUrl3);
			}
			record.setGoodsSatisfaction(model.getGoodsSatisfaction()); //商品评分
			record.setConsultContent(model.getConsultContent()); //评价内容
			record.setLogisticsScore(model.getLogisticsScore()); //物流评分
			record.setServiceScore(model.getServiceScore()); //服务评分
		//足迹信息
		}else{
			record.setGoodsId(model.getGoodsId());//商品ID
		}
		record.setType(model.getType()); //类型
		record.setCreater(model.getCreater()); //创建人
		record.setCreateTime(new Date());
		return record;
	}
	
	
	/**
	 * 测试
	 * @param args
	 */
	@RequestMapping(value="test")
	public String test(){
	
		ConsultComment c = new ConsultComment();
		c.setType("2");
		c.setGoodsId(1);
		c.setConsultContent("该商品非常不错！很棒！！");
		c.setLogisticsScore("5分");
		c.setServiceScore("5分");
		c.setLogisticsScore("5分");
		
	/*	c.setType("3");
		c.setGoodsId("1");*/
		
		
		String param = JsonUtils.objectToJson(c);
		this.addConsultComment(null, param);
		return null;
	}
	
	
	
	/***
	 * 
	 * 1、订单列表：猜你喜欢的商品【1、 获取曾经浏览的商品，2、如果为空，则获取热销的商品【暂未做查询】】
	 * 2、订单详情： 最近浏览过的商品
	 * @param request
	 * @param currPage
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value="/latelyTracks")
	@ResponseBody
	public Object latelyTracks(HttpServletRequest request){
		List<ConsultComment> data = null;
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		try {
			//判断会员是否登录
			Map<String, Object> paramMap = new HashMap<String, Object>();
			String memberId = request.getParameter("memberId");
			if(memberId!=null){
				paramMap.put("creater", memberId);
			}
			paramMap.put("type", Constants.TYPE_C);  //3、我的足迹' 
			data = consultCommentService.queryLatelyTracks(paramMap);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, data);
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询最近浏览过的商品数据异常"+e);
			throw new ScBizException("查询最近浏览过的商品数据异常！", e);
		}
		return resultMap;
	}
	
	
	/****
	 * 删除足迹信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteFootprint")
	@ResponseBody
	public Object deleteFootprint(HttpServletRequest request){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();	
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			String memberId = request.getParameter("memberId");
			if(memberId==null || "".equals(memberId)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				logger.warn("json的param参数传递出错！");
				return resultMap;
			}
			paramMap.put("memberId", memberId);
			int j = 0;
			String id = request.getParameter("footprintId");
			if(id==null || "".equals(id)){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				logger.warn("json的param参数传递出错！");
				return resultMap;
			}
			
			String idTemp[] = id.split(",");
			for (int i = 0; i < idTemp.length; i++) {
				Integer idd = new Integer(idTemp[i]);
				j = consultCommentService.deleteConsult(idd);
			}
			if(j>0){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				resultMap.put("data", id);
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_DELETE);
			}
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("删除足迹数据异常"+e);
			throw new ScBizException("删除足迹数据异常！", e);
		}
		return resultMap;
	}
	
	
	/***
	 * 
	 * 追加评论接口
	 * 获取第一次评论的信息，返回给App端
	 * @param model
	 * @param orderId
	 * @param goodsId
	 * @return
	 */
	@RequestMapping(value="/addEvaluate")
	@ResponseBody
	public Map<String, Object> addEvaluate(String orderId,String goodsId){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			if((orderId==null && "".equals(orderId)) || (goodsId==null && "".equals(goodsId))){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			ConsultComment comment = new ConsultComment();
			comment.setOrderId(orderId);
			comment.setGoodsId(new Integer(goodsId));
			List<ConsultComment> commentList = consultCommentService.selectCommentByParam(comment);
			if(commentList!=null && commentList.size()>0){
				resultMap.put("data", commentList);
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			}
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询咨询、评价信息数据异常"+e);
			throw new ScBizException("查询咨询、评价信息数据异常！", e);
		}
		return resultMap;
	}
	
}
